<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\BannerModel;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    protected $form_name = [
        'img_src','banner_title','banner_url','banner_description'
    ];
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.banner.index');
    }

    public function list(Request $request)
    {
        $page = $request->page ? : 1;
        $limit = $request ->limit ? : 10;

        $data['code'] = 0;
        $data['msg'] = '成功';
        $data['count'] = BannerModel::count();
        $data['data'] = BannerModel::skip($limit * ($page -1))
            ->take($limit)
            ->get();
        return $data;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.banner.add');
    }

    /**
     * @param Request $request
     * @return array
     */
    public function store(Request $request)
    {
        $data = $request->only($this->form_name);
        if (empty($data['img_src'])){
            return $this->res_msg(2, 'banner没有上传');
        }
        $Banner = new BannerModel();
        foreach ($this->form_name as $v){
            $Banner -> $v = $data[ $v ];
        }
        if ( $Banner -> save() ){
            return $this->res_msg(0, '成功');
        }else {
            return $this->res_msg(1, '失败');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $banner = BannerModel::findOrFail($id);

        $data['info'] = ['id'=>$id];
        foreach ($this->form_name as $v){
            $data['info'][$v] = old($v, $banner->$v);
        }
        return view('admin.banner.edit')->with('data',$data);
    }

    /**
     * @param Request $request
     * @param $id
     * @return array
     */
    public function update(Request $request, $id)
    {
        $banner = BannerModel::findOrFail($id);
        foreach ($this->form_name as $v){
            $banner -> $v = $request->get($v);
        }
        if ($banner->save()){
            return $this->res_msg(0, '修改成功');
        } else {
            return $this->res_msg(1, '修改失败');
        }
    }

    /**
     * @param $id
     * @return array
     */
    public function destroy($id)
    {
        $banner = BannerModel::findOrFail($id);
        if ($banner->delete()){
            return $this->res_msg(0, '删除成功');
        }else{
            return $this->res_msg(1, '删除失败');
        }
    }
}
